package com.lsk.applet;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.wxaapp.api.WxaOrder;
import com.jfinal.wxaapp.api.WxaPayApi;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.jfinal.wxaapp.api.WxaUserApi;
import com.lsk.admin.member.MemberService;
import com.lsk.admin.order.OrderController;
import com.lsk.admin.shop.ShopServices;
import com.lsk.util.*;
import com.lsk.weixin.SdkRewrite.shakearound.WxaTemplateApiRewrite;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class AppletService
{
    static ShopServices shopServices = new ShopServices();
    static MemberService memberService = new MemberService();
    static OrderController orderController =new OrderController();
    Cache cache = Redis.use("ACTIVITYUSER");
    private static String jsCode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

    public ApiResult getSessionKeyService(String jsCode, String shopId)
    {
        Map<String, String> params = new HashMap();
        Record applet = getAppletInfo(shopId, false);

        params.put("appid", applet.getStr("appId"));

        params.put("secret", applet.getStr("appSecret"));
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");
        String para = PaymentKit.packageSign(params, false);
        String url = jsCode2sessionUrl + "?" + para;
        ApiResult apiResult = new ApiResult(HttpUtils.get(url));
        Syslog.info(apiResult.getJson());

        return apiResult;
    }

    public Record getAppletInfo(String shopId, boolean userCache)
    {
        String sql = "SELECT * from weixin_public_account_info where shopId='" + shopId + "' and type=1 ";

        Record record = new Record();
        if (userCache) {
            record = Db.findFirstByCache("tenMinutes", MD5.md5(sql), sql);
        } else {
            record = Db.findFirst(sql);
        }
        return record;
    }

    public Map decodeService(String sessionKey, String encryptedData, String ivStr, String shopId, String parentId)
    {
        Map resultMap = new HashMap();

        WxaUserApi wxaUserApi = new WxaUserApi();

        ApiResult apiResult = wxaUserApi.getUserInfo(sessionKey, encryptedData, ivStr);

        Record wxaConfig = getWxaConfig(shopId);

        Map<String, String> params = new HashMap();
        params.put("appid", wxaConfig.getStr("appId"));

        String unionid = (String)apiResult.get("openId");
        String openId = (String)apiResult.get("openId");
        String nickName = (String)apiResult.get("nickName");
        String avatarUrl = (String)apiResult.get("avatarUrl");
        String apply="0";
        nickName = EmojiFilter.filterEmoji(nickName);
        Record member = getMemberInfo(unionid, shopId);

        if (member == null)
        {
            member = new Record();
            member.set("unionid", unionid).set("openId", openId).set("appId", wxaConfig.getStr("appId"))
                    .set("heardUrl", avatarUrl).set("name", nickName).set("shopId", shopId)
                    .set("parentId", parentId).set("apply",apply);
            saveMemberService(member);
        }
        resultMap.put("apiResult", apiResult);
        resultMap.put("member", member);
        return resultMap;
    }

    public Map phoneDecodeService(String sessionKey, String encryptedData, String ivStr)
    {
        String result = AES.AESBaseDncode(ivStr, sessionKey, encryptedData);
        Syslog.info(result);

        Map resultMap = JsonUtil.getMapFromJsonObjStr(result);

        return resultMap;
    }

    public ReturnData saveMemberPhoneService(String memberId, String phone)
    {
        boolean sa = false;

        Record record = new Record().set("id", memberId).set("tel", phone);

        sa = Db.update("yx_member", "id", record);

        return new ReturnData(sa);
    }

    public boolean saveMemberService(Record member)
    {
        boolean sa = false;
        String id = member.getStr("id");
        if (("".equals(id)) || (id == null))
        {
            member.set("id", UtilUUID.getUUID().substring(18));
            sa = Db.save("yx_member", "id", member);
        }
        else
        {
            sa = Db.update("yx_member", "id", member);
        }
        return sa;
    }

    public Record getMemberInfo(String unionId, String shopId)
    {
        String sql = "SELECT *from yx_member where unionId='" + unionId + "' and shopId='" + shopId + "'";
        Record member = Db.findFirst(sql);
        return member;
    }

    public ReturnData upMemberInfoService(Map<String, String> map)
    {
        ReturnData returnData = new ReturnData();

        String unionid = ((String)map.get("unionid"));

        String shopId = ((String)map.get("shopId"));

        Record member = getMemberInfo(unionid, shopId);
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            System.out.println("Key = " + (String)entry.getKey() + ", Value = " + ((String)entry.getValue()));
            member.set((String)entry.getKey(), EmojiFilter.filterEmoji(((String)entry.getValue())));
        }
        boolean sa = saveMemberService(member);
        if (sa)
        {
            returnData.setCode("000000");

            returnData.setMsg("更新信息成功");

            returnData.setData(member);
        }
        else
        {
            returnData.setCode("111111");

            returnData.setMsg("授权失败，请再次点击");
        }
        return returnData;
    }

    public ReturnData ticketListService(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();

        String[] keys = (String[])map.get("key");
        String key = "";
        if (keys != null) {
            key = keys[0];
        }
        String page = ((String[])map.get("page"))[0];

        String shopId = ((String[])map.get("shopId"))[0];

        String field = ((String[])map.get("field"))[0];

        String sort = ((String[])map.get("sort"))[0];

        String prefectureId = ((String[])map.get("prefectureId"))[0];

        String sql = "SELECT a.* from ticket a  JOIN prefecture_ticket b ON a.id=b.ticketId where state=1  and shopId='" + shopId + "'  ";
        if (!"".equals(key)) {
            sql = sql + "and `key` LIKE '%" + key + "%'";
        }
        if ((prefectureId != null) && (!"".equals(prefectureId))) {
            sql = sql + " AND b.prefectureId='" + prefectureId + "'";
        }
        sql = sql + " GROUP BY a.id";

        sql = sql + " order by " + field + "  " + sort;

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), 15, sql);
        if (pageUtil.getTotalRows() > 0)
        {
            returnData.setResult(true);
            for (int i = 0; i < pageUtil.getList().size(); i++)
            {
                Record record = (Record)pageUtil.getList().get(i);

                String imgPath = (String)record.get("imgPath");

                String[] pathArr = imgPath.split("\\|");

                record.remove(imgPath).set("imgPath", pathArr);

                pageUtil.getList().set(i, record);
            }
            returnData.setData(pageUtil.getList());
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData ticketListService1(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();

        String[] keys = (String[])map.get("key");
        String key = "";
        if (keys != null) {
            key = keys[0];
        }
        String page = ((String[])map.get("page"))[0];

        String shopId = ((String[])map.get("shopId"))[0];

        String field = ((String[])map.get("field"))[0];

        String sort = ((String[])map.get("sort"))[0];

        String navigationId = ((String[])map.get("prefectureId"))[0];

        String sql = "SELECT a.* from ticket a  where a.state=1 and  shopId='" + shopId + "'  ";
        if (!"".equals(key)) {
            sql = sql + "and `key` LIKE '%" + key + "%'";
        }
        if ((navigationId != null) && (!"".equals(navigationId))) {
            sql = sql + " AND classId='" + navigationId + "'";
        }
        sql = sql + " GROUP BY a.id";

        sql = sql + " order by " + field + "  " + sort;

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), 15, sql);
        if (pageUtil.getTotalRows() > 0)
        {
            returnData.setResult(true);
            for (int i = 0; i < pageUtil.getList().size(); i++)
            {
                Record record = (Record)pageUtil.getList().get(i);

                String imgPath = (String)record.get("imgPath");

                String[] pathArr = imgPath.split("\\|");

                record.remove(imgPath).set("imgPath", pathArr);

                pageUtil.getList().set(i, record);
            }
            returnData.setData(pageUtil.getList());
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData getCouponService(Map<String, String[]> map)
    {
        boolean get = false;

        String memberId = ((String[])map.get("memberId"))[0];

        String timeNumber = ((String[])map.get("timeNumber"))[0];

        String commodityId = ((String[])map.get("commodityId"))[0];

        String gameId = ((String[])map.get("gameId"))[0];

        String sql = "SELECT *from applet_rule where gameId='" + gameId + "' and maxSecond<=" + timeNumber;

        Record ruleRecod = Db.findFirst(sql);

        Record memberInfo = getMemberInfoById(memberId);

        Record commodityInfo = getCommodityInfoById(commodityId);

        Record gameRecord = getGameInfoById(gameId);

        Record coupon = new Record();

        String couponId = DateUtil.getDays() + Tools.getRandomNum();

        coupon.set("id", couponId).set("memberName", memberInfo.getStr("name")).set("memberId", memberId)
                .set("commodityId", commodityId).set("commodityName", commodityInfo.getStr("name"))
                .set("commodityPrize", commodityInfo.getStr("prize")).set("commodityLogoImg", commodityInfo.getStr("logoPath"))
                .set("discount", ruleRecod.getStr("discount")).set("type", gameRecord.getStr("type"))
                .set("createTime", new Date()).set("startDate", ruleRecod.getStr("startDate")).set("address", commodityInfo.getStr("address"))
                .set("endDate", ruleRecod.getStr("endDate")).set("command", ruleRecod.getStr("command"));

        get = Db.save("applet_coupon", "id", coupon);
        ReturnData returnData = new ReturnData(get);
        if (get) {
            returnData.setData(coupon);
        }
        return returnData;
    }

    public ReturnData couponListService(String id)
    {
        String sql = "SELECT *from yx_coupon  where id='" + id + "' ORDER BY state , createTime desc  ";

        List<Record> list = Db.find(sql);

        ReturnData returnData = new ReturnData(true);

        returnData.setData(list);

        return returnData;
    }

    public Record getMemberInfoById(String id)
    {
        Record record = Db.findFirst("select *from yx_member where id='" + id + "'");

        return record;
    }

    public Record getCommodityInfoById(String id)
    {
        String sql = "select *from applet_commodity where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    public Record getGameInfoById(String id)
    {
        String sql = "select *from applet_game where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    public ReturnData couponInfoService(String couponId)
    {
        String sql = "SELECT *from applet_coupon where id='" + couponId + "'";

        Record record = Db.findFirst(sql);

        ReturnData returnData = new ReturnData(true);

        returnData.setData(record);

        return returnData;
    }

    public ReturnData couponUseService(String couponId)
    {
        Record record = new Record().set("id", couponId).set("state", Integer.valueOf(1));

        boolean up = Db.update("applet_coupon", "id", record);

        return new ReturnData(up);
    }

    public void memberShareService(String memberId)
    {
        Record memberInfo = getMemberInfoById(memberId);

        shareCoupon(memberInfo);
    }

    public ReturnData memberAddressListService(String memberId)
    {
        String sql = "SELECT *from yx_member_address where memberId='" + memberId + "'";

        List<Record> list = Db.find(sql);

        ReturnData returnData = new ReturnData();
        if (list.size() > 0)
        {
            returnData.setResult(true);

            returnData.setData(list);
        }
        returnData.setResult(false);
        returnData.setMsg("暂无数据");

        return returnData;
    }

    public ReturnData saveAddressService(Map<String, String[]> map)
    {
        String id = ((String[])map.get("id"))[0];

        String userName = ((String[])map.get("userName"))[0];

        String telNumber = ((String[])map.get("telNumber"))[0];

        String detailInfo = ((String[])map.get("detailInfo"))[0];

        String memberId = ((String[])map.get("memberId"))[0];

        String defaultAddress = ((String[])map.get("defaultAddress"))[0];

        Record record = new Record().set("userName", userName).set("telNumber", telNumber).set("detailInfo", detailInfo).set("memberId", memberId).set("defaultAddress", defaultAddress);

        boolean sa = false;
        if ("".equals(id))
        {
            record.set("id", UtilUUID.getUUID());

            sa = Db.save("yx_member_address", "id", record);
        }
        else
        {
            sa = Db.update("yx_member_address", "id", record);
        }
        ReturnData returnData = new ReturnData(sa);

        return returnData;
    }

    public ReturnData memberCouponService(String memberId, int page, String state)
    {
        ReturnData returnData = new ReturnData();

        String sql = "SELECT ycard.id ,ycard.creatime,ycard.memberId,ycard.shopId,\nycard.state,ycard.verificationTime,yx.`name`,yx.remark,yx.giveType,yx.startTime,yx.endTime,yx.mixMoney,yx.money\n  from yx_coupon_card ycard LEFT JOIN yx_coupon yx on ycard.couponId=yx.id \nwhere ycard.memberId='" + memberId + "' and  ycard.state='" + state + "'  ORDER BY ycard.creatime desc ";

        PageUtil pageUtil = new PageUtil(page, 20, sql);
        if (pageUtil.getTotalRows() > 0)
        {
            returnData.setResult(true);

            returnData.setData(pageUtil.getList());
        }
        else
        {
            returnData.setResult(true);

            returnData.setMsg("暂无数据");
        }
        return returnData;
    }

    public ReturnData getMemberInfoService(String unionId)
    {
        ReturnData returnData = new ReturnData(true);

        String sql = "SELECT *from yx_member where unionId='" + unionId + "'";

        Record member = Db.findFirst(sql);



        if (member != null && "undefined".equals(unionId)==false && "".equals(unionId)==false)
        {
            returnData.setData(member);

            returnData.setCode("000000");
        }
        else
        {
            returnData.setCode("111111");
        }
        return returnData;
    }

    public ReturnData shopService(String id)
    {
        String sql = "SELECT * from shop where id='" + id + "'";

        Record record = Db.findFirst(sql);

        ReturnData returnData = new ReturnData(true);

        returnData.setData(record);

        return returnData;
    }

    public ReturnData memberServoceService(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();

        String id = ((String[])map.get("memberId"))[0];

        String tel = ((String[])map.get("tel"))[0];

        String name = ((String[])map.get("name"))[0];

        boolean result = false;

        result = Db.update("yx_member", "id", new Record().set("id", id).set("tel", tel).set("name", name).set("apply", "1"));

        memberService.distributorAudit(id, "0", "申请中");

        returnData.setResult(result);
        if (result)
        {
            returnData.setMsg("成功");
            returnData.setCode("000000");
        }
        else
        {
            returnData.setMsg("失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    public Record findTicketdetail(String id)
    {
        String sql = "SELECT * FROM ticket WHERE id='" + id + "'";
        Record record = Db.findFirst(sql);

        new GlobalParameter();String projectPath = GlobalParameter.projectPath;


        try {
            String descriptionPath = projectPath + "/commodity-message/content-txt/" + record.getStr("id") + ".txt";





            Syslog.info("详情内容路径：： "+descriptionPath);

            String description = FileUtil.readTxt(descriptionPath);

            record.set("description", description);
        }catch (Exception e){


                    Syslog.error(e);

        }





        String sku = record.get("ticketSku")+"";

        List<Record> skuList =  JSON.parseArray(sku,Record.class);
        String lablesql = "SELECT * FROM ticket_label WHERE ticketId ='" + id + "'";
        List<Record> lableList = Db.find(lablesql);
        record.set("lableList", lableList);
        if (skuList.size() > 0)
        {
            List<Record> methodList = new ArrayList();
            List<Record> peopleList = new ArrayList();
            List<Record> typeList = new ArrayList();
            for (int i = 0; i < skuList.size(); i++)
            {
                String methodsql = "SELECT * FROM ticket_method WHERE id='" + ((Record)skuList.get(i)).get("ticket_methodId") + "'";
                Record ticketmethod = Db.findFirst(methodsql);
                methodList.add(ticketmethod);
                String peoplesql = "SELECT * FROM ticket_person_type WHERE id='" + ((Record)skuList.get(i)).get("ticket_person_typeId") + "'";
                Record ticketPeople = Db.findFirst(peoplesql);
                peopleList.add(ticketPeople);
                String ticket_typesql = "SELECT * FROM ticket_type WHERE id='" + ((Record)skuList.get(i)).get("ticket_typeId") + "'";
                Record ticketTYPE = Db.findFirst(ticket_typesql);
                typeList.add(ticketTYPE);
            }
            Set<Record> middleHashSet = new HashSet(methodList);

            List<Record> aftermethodList = new ArrayList(middleHashSet);
            record.set("aftermethodList", aftermethodList);

            Set<Record> middleHashSet1 = new HashSet(peopleList);

            List<Record> afterpeopleList = new ArrayList(middleHashSet1);
            record.set("afterpeopleList", afterpeopleList);

            Set<Record> middleHashSet2 = new HashSet(typeList);

            List<Record> aftertypeList = new ArrayList(middleHashSet2);
            record.set("aftertypeList", aftertypeList);
        }
        record.set("sku", skuList);
        String lunboSql = "SELECT a.* FROM shop_commodity_imgpath a WHERE commodityId='" + id + "'";
        List<Record> lunboList = Db.find(lunboSql);
        record.set("lunbo", lunboList);

        List<Record> peopleTypeList = findAllticketTypeBysysId("ticket_person_type", (String)record.get("shopId"));
        List<Record> ticket_typeList = findAllticketTypeBysysId("ticket_type", (String)record.get("shopId"));
        List<Record> ticket_methodList = findAllticketTypeBysysId("ticket_method", (String)record.get("shopId"));
        record.set("peopleTypeList", peopleTypeList);
        record.set("ticket_typeList", ticket_typeList);
        record.set("ticket_methodList", ticket_methodList);

        String shopId = (String)record.get("shopId");
        String shopSql = "SELECT a.serviceIcon FROM shop a WHERE id='" + shopId + "'";
        String serviceIconImg = Db.queryStr(shopSql);
        record.set("serviceIconImg", serviceIconImg);
        return record;
    }

    public List<Record> findAllticketTypeBysysId(String tableName, String shopId)
    {
        String sql = "  SELECT a.* FROM  " + tableName + " a  JOIN   shop b ON  a.shopId=b.id WHERE b.id='" + shopId + "'";
        List<Record> list = new ArrayList();
        try
        {
            list = Db.find(sql);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return list;
    }

    public ReturnData skuVsmoney(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();
        String ticket_person_typeId = ((String[])map.get("ticket_person_typeId"))[0];
        String ticket_typeId = ((String[])map.get("ticket_typeId"))[0];
        String ticket_methodId = ((String[])map.get("ticket_methodId"))[0];
        String ticketId = ((String[])map.get("ticketId"))[0];
        Record returnRecord = new Record();
        try
        {
            Record ticket = findTicketdetail(ticketId);
            List<Record> list = (List)ticket.get("sku");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++)
                {
                    Record record = (Record)list.get(i);
                    if ((ticket_methodId.equals(String.valueOf(record.get("ticket_methodId")))) && (ticket_person_typeId.equals(String.valueOf(record.get("ticket_person_typeId")))) &&
                            (ticket_typeId.equals(String.valueOf(record.get("ticket_typeId"))))) {
                        returnRecord.set("money", record.get("money"));
                    }
                }
            }
            if (returnRecord.get("money") == null) {
                returnRecord.set("money", ticket.get("money"));
            }
            returnData.setData(returnRecord);
            returnData.setCode("0");
            returnData.setMsg("请求成功");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public ReturnData generateorder(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();

        String ticketId = ((String[])map.get("ticketId"))[0];

        String memberId = ((String[])map.get("memberId"))[0];

        String number = ((String[])map.get("number"))[0];
        String money = ((String[])map.get("money"))[0];
        String visitName = ((String[])map.get("visitName"))[0];
        String visitPhone = ((String[])map.get("visitPhone"))[0];
        String isNeedIdnumber = ((String[])map.get("isNeedIdnumber"))[0];


        Date date=new  Date(); //取时间
        Calendar  calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,30); //把日期往后增加一天,整数  往后推,负数往前移动
        //Date endtime=calendar.getTime(); //售票有效期

        String checkCode=getCheckCode(); //核销码
        String checkStatus="1";
        String couponId = "";
        if (map.get("couponId") != null)
        {
            couponId = ((String[])map.get("couponId"))[0];
            if (!"".equals(couponId)) {
                clipCoupons(couponId, memberId);
            }
        }
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Record ticket = findTicketdetail(ticketId);
        String shopId = (String)ticket.get("shopId");
        Date endTime=ticket.get("endTime");
        String spotName=ticket.get("spotName");
        String personType=ticket.get("personType");
        Record yx_order = new Record();

        Record member = getMemberInfoById(memberId);
        String parentId = "";
        if (member.get("parentId") != null) {
            parentId = (String)member.get("parentId");
        }
        try
        {
            yx_order.set("commodityId", ticketId).set("money", money).set("memberId", memberId).set("personType",personType).set("number", number).set("createTime", date).set("spotName",spotName).set("endTime",endTime).set("checkCode",checkCode).set("checkStatus",checkStatus).set("parentId", parentId).set("shopId", shopId).set("id", DateUtil.getDays().substring(4) + Tools.getRandomNum()).set("couponId", couponId).set("updateTime", new Date()).set("visitName", visitName).set("visitPhone", visitPhone);
            if ("1".equals(isNeedIdnumber))
            {
                String visitIdnumber = ((String[])map.get("visitIdnumber"))[0];
                yx_order.set("visitIdnumber", visitIdnumber);
            }
            boolean sa = Db.save("yx_order", yx_order);
            if (sa)
            {
                returnData.setResult(sa);
                returnData.setMsg("待支付订单创建成功");
                returnData.setData(yx_order);
            }
            else
            {
                returnData.setResult(sa);
                returnData.setMsg("待支付订单创建失败");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setCode("111111");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }
    //生成随机六位数核销码
    public String getCheckCode() {
        String ZiMu = "qwertyuiopasdfghjklzxcvbnm1234567890";
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(ZiMu.length());
            char c = ZiMu.charAt(index);
            result += c;
        }
        return result;
    }


    public ReturnData orderPayService(Map<String, String[]> map)
    {
        String orderId = ((String[])map.get("orderId"))[0];

        String openId = ((String[])map.get("openId"))[0];

        String orderSql = "SELECT *from yx_order where id='" + orderId + "'";

        Record order = Db.findFirst(orderSql);

        ReturnData returnData = wxaPayServicePostage(order, openId);

        return returnData;
    }

    public ReturnData wxaPayServicePostage(Record order, String openId)
    {
        ReturnData returnData = new ReturnData();
        try
        {
            BigDecimal bigDecimalMoney = new BigDecimal(order.getDouble("money").doubleValue()).multiply(new BigDecimal(100.0D));

            int money = bigDecimalMoney.setScale(2, 0).intValue();
            String ip = "127.0.0.1";

            String orderId = order.getStr("id").trim();

            String shopId = order.getStr("shopId");

            Record wxaConfig = getWxaConfig(shopId);

            String signKey = wxaConfig.getStr("payKey").trim();

            String appId = wxaConfig.getStr("appId").trim();

            order.set("appId", appId);

            Db.update("yx_order", "id", order);

            String appSecret = wxaConfig.getStr("appSecret").trim();

            String domain = wxaConfig.getStr("domain").trim();

            String mchId = wxaConfig.get("mchId").toString().trim();

            WxaOrder wxaOrder = new WxaOrder(appId, mchId, signKey);

            wxaOrder.setOpenId(openId);

            wxaOrder.setBody("在线购票");

            wxaOrder.setSpbillCreateIp(ip);

            wxaOrder.setTotalFee(money + "");

            wxaOrder.setOutTradeNo(orderId);

            wxaOrder.setNotifyUrl("http://" + domain.replace("http://", "") + "/applet/payCallBack");

            WxaPayApi wxaPayApi = new WxaPayApi();

            Map<String, String> resultMap = wxaPayApi.unifiedOrder(wxaOrder);

            String templateKey = order.getStr("id") + "templateKey";

            String prepay_id = (String)resultMap.get("package");

            this.cache.setex(templateKey, 864000, prepay_id);

            Syslog.info(resultMap.toString());

            resultMap.put("orderId", orderId);

            returnData.setData(resultMap);

            returnData.setMsg("请求异常");

            returnData.setCode("000000");
        }
        catch (Exception e)
        {
            Syslog.error(e);
            returnData.setMsg("请求异常，请联系管理员");
            returnData.setCode("555555");
        }
        return returnData;
    }

    public Record getWxaConfig(String shopId)
    {
        String appletConfigSql = "SELECT *from weixin_public_account_info where type=1 and shopId='" + shopId + "'";

        Record config = Db.findFirst(appletConfigSql);

        return config;
    }

    public Record getWxConfig(String shopId)
    {
        String appletConfigSql = "SELECT *from weixin_public_account_info where type=0 and shopId='" + shopId + "'";

        Record config = Db.findFirst(appletConfigSql);

        return config;
    }

    public ReturnData myOrder(String memberId)
    {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT a.*,b.`name`,SUBSTRING_INDEX(SUBSTRING_INDEX(b.imgPath,'|',2),'|',-1) as img FROM yx_order a LEFT JOIN ticket b ON  a.commodityId=b.id WHERE a.memberId='" + memberId + "'";
        try
        {
            List<Record> list = Db.find(sql);
            returnData.setData(list);
            returnData.setCode("0");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public Record getOrderInfoService(String id)
    {
        String sql = "select *from yx_order where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    public ReturnData oneClassTypeService(String shopId)
    {
        String sql = "SELECT *from navigation where shopId='" + shopId + "' and parentId='0' ORDER BY number";

        List<Record> list = Db.find(sql);

        ReturnData returnData = new ReturnData();
        if (list.size() > 0)
        {
            Record first = (Record)list.get(0);

            String id = first.getStr("id");

            ReturnData two = twoClassTypeService(id);

            Map resultMap = new HashMap();

            resultMap.put("one", list);

            resultMap.put("two", two);

            returnData.setResult(true);

            returnData.setData(list);
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData twoClassTypeService(String parentId)
    {
        String sql = "SELECT *from navigation where parentId='" + parentId + "' ORDER BY number";

        List<Record> list = Db.find(sql);

        ReturnData returnData = new ReturnData();
        if (list.size() > 0)
        {
            returnData.setResult(true);

            returnData.setData(list);
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData indexDataService(String shopId)
    {
        List<Record> slideShowList = shopServices.slideShowListService(shopId);

        List<Record> prefectureList = prefectureList(shopId);

        Map resultMap = new HashMap();

        resultMap.put("slideShowList", slideShowList);

        resultMap.put("prefectureList", prefectureList);

        ReturnData returnData = new ReturnData(true);

        returnData.setData(resultMap);

        return returnData;
    }

    public List<Record> prefectureList(String shopId)
    {
        String sql = "SELECT *from ticket_prefecture where shopId='" + shopId + "' order by number ";

        List<Record> list = Db.find(sql);

        return list;
    }

    public ReturnData hotTicketService(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();

        String shopId = ((String[])map.get("shopId"))[0];

        String page = ((String[])map.get("page"))[0];

        String[] keys = (String[])map.get("key");
        String key = "";
        if (keys != null) {
            key = keys[0];
        }
        String sql = "SELECT *from ticket where shopId='" + shopId + "' and  state='1'";

        String countSql = "SELECT count(*) from ticket where shopId='" + shopId + "'  and  state='1'";
        if (!"".equals(key))
        {
            sql = sql + "and `key` LIKE '%" + key + "%'";
            countSql = countSql + "and `key` LIKE '%" + key + "%'";
        }
        sql = sql + "  ORDER BY hotNumber asc ";

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), 15, sql, countSql);
        if (pageUtil.getTotalRows() > 0)
        {
            for (int i = 0; i < pageUtil.getList().size(); i++)
            {
                Record record = (Record)pageUtil.getList().get(i);

                String imgPath = (String)record.get("imgPath");

                String[] pathArr = imgPath.split("\\|");

                record.remove(imgPath).set("imgPath", pathArr);

                pageUtil.getList().set(i, record);
            }
            returnData.setResult(true);

            returnData.setData(pageUtil.getList());
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData payCoupon(Record memberInfo)
    {
        List<Record> memberlist = new ArrayList();
        ReturnData returnData1 = new ReturnData();
        try
        {
            String shopId = memberInfo.getStr("shopId");

            String sql = "SELECT *from yx_coupon  where shopId='" + shopId + "' and state=0 and giveType=0";

            List<Record> list = Db.find(sql);
            for (int i = 0; i < list.size(); i++)
            {
                Record temp = (Record)list.get(i);

                ReturnData returnData = giveMemberCoupon(memberInfo, temp);
                if (returnData.isResult()) {
                    memberlist.add(temp);
                }
            }
            if (memberlist.size() > 0)
            {
                returnData1.setResult(true);
                returnData1.setData(memberlist);
                return returnData1;
            }
        }
        catch (Exception e)
        {
            returnData1.setResult(false);

            Syslog.error(e);
        }
        returnData1.setResult(false);
        return returnData1;
    }

    public void shareCoupon(Record memberInfo)
    {
        ReturnData returnData = new ReturnData();
        try
        {
            String shopId = memberInfo.getStr("shopId");

            String sql = "SELECT *from yx_coupon  where shopId='" + shopId + "' and state=0 and giveType=1";

            List<Record> list = Db.find(sql);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++)
                {
                    Record temp = (Record)list.get(i);

                    giveMemberCoupon(memberInfo, temp);
                }
            }
        }
        catch (Exception e)
        {
            Syslog.error(e);
        }
    }

    public ReturnData giveMemberCoupon(Record memberInfo, Record coupon)
    {
        ReturnData returnData = new ReturnData();

        String checkSql = "SELECT *from yx_coupon_card where couponId='" + coupon.getStr("id") + "' and memberId='" + memberInfo.getStr("id") + "'";

        Record record = Db.findFirst(checkSql);
        if (record == null)
        {
            Record couponCard = new Record().set("memberId", memberInfo.getStr("id")).set("couponId", coupon.getStr("id")).set("shopId", memberInfo.getStr("shopId"));

            boolean sa = Db.save("yx_coupon_card", "id", couponCard);
            if (!sa)
            {
                Syslog.error(
                        "向会员发放优惠券" + JsonUtil.getJsonStr(memberInfo) + "失败，优惠券信息为" + JsonUtil.getJsonStr(coupon));
            }
            else
            {
                returnData.setResult(true);
                return returnData;
            }
        }
        else
        {
            Syslog.info("该会员已经领取过该优惠券");
        }
        returnData.setResult(false);
        return returnData;
    }

    public ReturnData waitCouponService(String memberId, String shopId, int giveType)
    {
        ReturnData returnData = new ReturnData();

        String couponSql = "SELECT\n\tyc.*\nFROM\n\tyx_coupon yc\n\nWHERE\n\tyc.giveType = " + giveType + "\n  \n  and shopId='" + shopId + "' \n\n  and yc.id not in (\n\n\tSELECT ycc.couponId from yx_coupon_card ycc where ycc.memberId='" + memberId + "')";

        List<Record> list = Db.find(couponSql);
        if (list.size() > 0)
        {
            returnData.setResult(true);

            returnData.setData(list);
        }
        else
        {
            returnData.setResult(false);
        }
        return returnData;
    }

    public ReturnData memberGetCouponService(String memberId, String couponId, String shopId)
    {
        String sql = "select *from yx_coupon_card where memberId='" + memberId + "' and couponId='" + couponId + "' and shopId='" + shopId + "' ";

        Record record = Db.findFirst(sql);

        boolean sa = true;
        if (record == null)
        {
            Record couponCard = new Record().set("memberId", memberId).set("couponId", couponId).set("shopId", shopId).set("state", Integer.valueOf(0));

            sa = Db.save("yx_coupon_card", "id", couponCard);
        }
        return new ReturnData(sa);
    }

    public ReturnData processingOrder(String orderId, String transaction_id)
    {
        ReturnData returnData = new ReturnData();
        Record order = getOrderInfoService(orderId);
        try
        {
            if (order != null)
            {
                if (!"0".equals(order.get("state"))) {
                    return returnData;
                }
                order.remove("state");
                order.set("state", "1");
                order.remove("updateTime");
                order.set("updateTime", new Date()).set("wxId", transaction_id);
                Db.update("yx_order", order);

                String memberId = (String)order.get("memberId");

                String sql = "SELECT * FROM yx_member WHERE  id='" + memberId + "'";
                Record memberinfo = Db.findFirst(sql);




                String ticketId = (String)order.get("commodityId");
                String ticketSql = "SELECT a.* FROM ticket a  WHERE a.id='" + ticketId + "'";
                Record ticket = Db.findFirst(ticketSql);

                int salNum = Integer.parseInt(String.valueOf(ticket.get("salNum")));
                int inventory = Integer.parseInt(String.valueOf(ticket.get("inventory")));
                ticket.remove("salNum").remove("inventory");

                ticket.set("salNum", Integer.valueOf(salNum + 1)).set("inventory", Integer.valueOf(inventory - 1));
                Db.update("ticket", ticket);

                String code = memberinfo.get("name") + "——购买了本平台的——" + ticket.get("name");
                String shopId = (String)order.get("shopId");
                String shopSql = "SELECT a.*  FROM shop  a WHERE id='" + shopId + "'";
                Record shop = Db.findFirst(shopSql);
                //商家短信信息
                String phone = (String)shop.get("phone");
                String shangjiaName = String.valueOf(shop.get("merchant_name"));
                String memberName = String.valueOf(order.get("visitPhone"));
                String ticketName = (String)ticket.get("name");
                //用户订单短信息
                String writeoff=ticket.get("writeoff");


                String parentId = "";
                Record memberInfo = getMemberInfoById(memberId);
                if (memberInfo.get("parentId") != null) {
                    parentId = (String)memberInfo.get("parentId");
                }




                sendOrderTemplate(memberinfo, order);



                if ( writeoff.equals("0")){
                    DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    String phones= order.get("visitPhone");        //用户手机号
                    String name=(String)ticket.get("name");            //商品名
                    String number=String.valueOf(order.get("number")); //购买数量
                    String checkCode=order.get("checkCode"); //核销码
                    String create=sdf.format(order.get("createTime")); //核销起始时间
                    String end=sdf.format(order.get("endTime")); //核销结束时间

                    boolean blogs = SendSMSUtils.sends(phones, name, number, checkCode, create, end).booleanValue();

                    order.remove("deliverystatus");
                    order.set("deliverystatus", "1");
                    order.remove("order");
                    order.set("state", "2");
                    Db.update("yx_order", order);

                    returnData =rebate(parentId, order);

                }else{

                    boolean blog = SendSMSUtil.send(phone, shangjiaName + "商家", memberName, ticketName).booleanValue();

                }

                returnData.setResult(true);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public ReturnData rebate(String parentId, Record order)
    {
        ReturnData returnData = new ReturnData();

        int Rebatemoney = 0;
        try
        {
            if ((parentId != null) && (!"".equals(parentId)))
            {
                String parentsql = "SELECT * FROM yx_member WHERE  id='" + parentId + "'";
                Record parentMember = Db.findFirst(parentsql);
//                String twoparentId = parentMember.getStr("parentId");

                String ticketsql = "SELECT * FROM ticket WHERE id='" + order.get("commodityId") + "'";
                Record ticket = Db.findFirst(ticketsql);

                BigDecimal onebigDecimal = CompuUtils.multiply(String.valueOf(ticket.get("oneprofits")), "100")
                        .multiply(new BigDecimal(order.getInt("number").intValue()));

                int b = onebigDecimal.compareTo(BigDecimal.ZERO);
                if (b == 1) {
                    if ("2".equals(String.valueOf(parentMember.get("apply"))))
                    {
                        int rebateType = 0;
                        int num = numberRebates(parentId, String.valueOf(order.get("id")));
                        if (num > 10) {
                            rebateType = 1;
                        }
                        shopServices.payRebateRedPack(String.valueOf(order.get("shopId")), String.valueOf(parentMember.get("payOpenId")), String.valueOf(onebigDecimal), rebateType, parentId, String.valueOf(order.get("id")), String.valueOf(order.get("commodityId")));

                        Syslog.info(parentMember.get("name") + "获得微信红包" + ticket.get("oneprofits") + "元");
                        Rebatemoney += onebigDecimal.intValue();
                    }
                    else
                    {
                        Syslog.info(parentMember.get("name") + "未通过分销商审核");
                    }
                }
                String twoparentId = parentMember.getStr("parentId");
                if ((twoparentId != null) && (!"".equals(twoparentId)))
                {
                    String twoparentsql = "SELECT * FROM yx_member WHERE  id='" + twoparentId + "'";
                    Record twoparentMember = Db.findFirst(twoparentsql);
                    BigDecimal twobigDecimal = CompuUtils.multiply(String.valueOf(ticket.get("twoprofits")), "100").multiply(new BigDecimal(order.getInt("number").intValue()));

                    int r = twobigDecimal.compareTo(BigDecimal.ZERO);
                    if ((r == 1) &&
                            ("2".equals(String.valueOf(twoparentMember.get("apply")))))
                    {
                        int rebateType = 0;
                        int num = numberRebates(parentId, String.valueOf(order.get("id")));
                        if (num > 10) {
                            rebateType = 1;
                        }
                        shopServices.payRebateRedPack(String.valueOf(order.get("shopId")), String.valueOf(twoparentMember.get("payOpenId")), String.valueOf(twobigDecimal), rebateType, twoparentId, String.valueOf(order.get("id")), String.valueOf(order.get("commodityId")));
                        Syslog.info(twoparentMember.get("name") + "获得微信红包" + ticket.get("twoprofits") + "元");
                        Rebatemoney += twobigDecimal.intValue();
                    }
                }
//                String twoparentId = parentMember.getStr("parentId");
//                if ((twoparentId != null) && (!"".equals(twoparentId)))
//                {
//                    String twoparentsql = "SELECT * FROM yx_member WHERE  id='" + twoparentId + "'";
//                    Record twoparentMember = Db.findFirst(twoparentsql);
//                    BigDecimal twobigDecimal = CompuUtils.multiply(String.valueOf(ticket.get("oneprofits")), "100").multiply(new BigDecimal(order.getInt("number").intValue()));
//
//                    int r = twobigDecimal.compareTo(BigDecimal.ZERO);
//                    if ((r == 1) &&
//                            ("2".equals(String.valueOf(twoparentMember.get("apply")))))
//                    {
//                        int rebateType = 0;
//                        int num = numberRebates(parentId, String.valueOf(order.get("id")));
//                        if (num > 10) {
//                            rebateType = 1;
//                        }
//                        shopServices.payRebateRedPack(String.valueOf(order.get("shopId")), String.valueOf(twoparentMember.get("payOpenId")), String.valueOf(twobigDecimal), rebateType, twoparentId, String.valueOf(order.get("id")), String.valueOf(order.get("commodityId")));
//                        Syslog.info(twoparentMember.get("name") + "获得微信红包" + ticket.get("oneprofits") + "元");
//                        Rebatemoney += twobigDecimal.intValue();
//                    }
//                }
                BigDecimal money = order.getBigDecimal("money");
                int ticketmoney = CompuUtils.multiply(String.valueOf(money), "100").intValue();

                int Surplusmoney = ticketmoney - Rebatemoney;

                String sql = "SELECT * FROM yx_member WHERE shopId='" + order.get("shopId") + "' AND withdrawer='1'";
                Record tixianMember = Db.findFirst(sql);
                String shopsql = "SELECT * FROM shop WHERE id='" + String.valueOf(order.get("shopId")) + "'";
                Record shop = Db.findFirst(shopsql);
                int pingMoney = 0;
                if ("按单".equals(String.valueOf(shop.get("charges_type")))) {
                    pingMoney = CompuUtils.multiply(String.valueOf(shop.get("per_commission")), "100").intValue();
                }
                if (tixianMember != null) {
                    if (Surplusmoney > 0)
                    {
                        int rebateType = 0;
                        int num = numberRebates(parentId, String.valueOf(order.get("id")));
                        if (num > 10) {
                            rebateType = 1;
                        }
                        shopServices.payRebateRedPack(String.valueOf(order.get("shopId")), String.valueOf(tixianMember.get("payOpenId")), String.valueOf(Surplusmoney - pingMoney), rebateType, String.valueOf(tixianMember.get("id")), String.valueOf(order.get("id")), String.valueOf(order.get("commodityId")));
                    }
                    else
                    {
                        Syslog.info("提现人payOpenId为空");
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public ReturnData cashWithdrawal(Map<String, String[]> map)
    {
        ReturnData returnData = new ReturnData();
        String memberId = ((String[])map.get("memberId"))[0];
        String type = ((String[])map.get("type"))[0];
        String money = ((String[])map.get("money"))[0];
        try
        {
            String sql = "SELECT * FROM yx_member WHERE id='" + memberId + "'";
            Record member = Db.findFirst(sql);
            String memberName = (String)member.get("name");
            if ("0".equals(type))
            {
                String remake = "收到返利红包";
                Record record = new Record();
                record.set("memberId", memberId).set("memberName", memberName).set("type", "0").set("remake", remake).set("creatTime", new Date())
                        .set("money", money).set("id", UtilUUID.getUUID());

                Db.save("yx_memeber_account_info", record);
                returnData.setResult(true);

                BigDecimal bigDecimal = CompuUtils.add(money, String.valueOf(member.get("balance")));
                member.remove("balance");
                member.set("balance", bigDecimal);
                Db.update("yx_member", member);
            }
            if ("1".equals(type))
            {
                int a = CompuUtils.compareTo(String.valueOf(member.get("balance")), money);
                if (a == 1)
                {
                    String remake = "余额提现";
                    Record record = new Record();
                    record.set("memberId", memberId).set("memberName", memberName).set("type", "1").set("remake", remake).set("creatTime", new Date())
                            .set("money", money).set("id", UtilUUID.getUUID());

                    Db.save("yx_memeber_account_info", record);
                    BigDecimal bigDecimal = CompuUtils.subtract(String.valueOf(member.get("balance")), money);
                    member.remove("balance");
                    member.set("balance", bigDecimal);
                    Db.update("yx_member", member);
                }
                else
                {
                    returnData.setResult(false);
                    returnData.setMsg("账户余额不足");
                    return returnData;
                }
            }
            returnData.setResult(true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public ReturnData receive(String memberId, String couponId, String shopId)
    {
        ReturnData returnData = new ReturnData();

        Record yx_coupon_card = new Record();
        try
        {
            yx_coupon_card.set("couponId", couponId).set("memberId", memberId).set("shopId", shopId).set("creatime", new Date()).set("state", "0");

            Db.save("yx_coupon_card", yx_coupon_card);

            returnData.setResult(true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public String QrCode(String shopId, String memberId, String ticketId)
            throws Exception
    {
        Record wxaConfig = getWxaConfig(shopId);

        String accessToken = (String)this.cache.get("wxaToken" + wxaConfig.getStr("appId"));
        if (accessToken == null)
        {
            accessToken = WxqrcodeUntil.getAccessToken();
            this.cache.setex("wxaToken" + wxaConfig.getStr("appId"), 3600, accessToken);
        }
        String qrcodeimg = WxqrcodeUntil.creatQRcode(accessToken, memberId, ticketId);

        return qrcodeimg;
    }

    public ReturnData availableCoupons(String ticketId, String memberId, String money)
    {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT a.*,c.memberId,a.id AS cardId FROM yx_coupon a  JOIN ticket_coupon b ON a.id=b.couponId  JOIN yx_coupon_card c ON c.couponId=a.id WHERE b.ticketId='" + ticketId + "' AND c.memberId='" + memberId + "' and c.state='0' and '" + money + "'>=a.mixMoney";
        try
        {
            List<Record> list = Db.find(sql);
            returnData.setData(list);
            returnData.setResult(true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public ReturnData clipCoupons(String couponId, String memberId)
    {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT  * FROM yx_coupon_card WHERE couponId='" + couponId + "' AND memberId='" + memberId + "'";
        Record record = Db.findFirst(sql);
        record.remove("state");
        record.set("state", "1");
        boolean b = Db.update("yx_coupon_card", record);
        returnData.setResult(b);
        return returnData;
    }

    public ReturnData upgradeMember(String parentId, String memberId)
    {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT a.* FROM yx_member a WHERE a.id='" + memberId + "'";
        try
        {

            Record member = Db.findFirst(sql);
            if ("0".equals(member.getStr("apply"))){//必须当前会员是普通会员

                member.remove("parentId");
                member.set("parentId", parentId);
                boolean b = Db.update("yx_member", member);
                returnData.setResult(b);

            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
            returnData.setResult(false);
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    public void sendOrderTemplate(Record member, Record order)
    {
        try
        {
            Record wxaConfig = getWxaConfig(order.getStr("shopId"));

            String templateKey = order.getStr("id") + "templateKey";
            Object obj = this.cache.get(templateKey);
            String prepay_id = obj.toString().trim();
            prepay_id = prepay_id.substring(10);

            String sql = "SELECT * FROM ticket WHERE id='" + order.getStr("commodityId") + "'";
            Record ticket = Db.findFirst(sql);
            WxaTemplate wxaTemplate = new WxaTemplate();
            wxaTemplate.setForm_id(prepay_id);
            wxaTemplate.setTouser(member.getStr("openId"));
            wxaTemplate.setTemplate_id(wxaConfig.getStr("payTemplateId"));
            wxaTemplate.add("keyword1", order.getStr("id"));
            wxaTemplate.add("keyword2", String.valueOf(ticket.get("name")));
            wxaTemplate.add("keyword3", order.getStr("number"));
            wxaTemplate.add("keyword4", order.getStr("money"));
            wxaTemplate.add("keyword5", order.getStr("visitName"));
            wxaTemplate.add("keyword6", order.getStr("visitPhone"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String createTime = String.valueOf(order.getStr("createTime")).substring(0, String.valueOf(order.getStr("createTime")).length() - 2);
            wxaTemplate.add("keyword7", createTime);
            WxaTemplateApiRewrite wxaTemplateApi = new WxaTemplateApiRewrite();

            ApiResult apiResult = wxaTemplateApi.send(wxaTemplate, order.getStr("appId"));
            Syslog.info(apiResult.getJson());
        }
        catch (Exception e)
        {
            Syslog.error(e);
        }
    }

    public void sendOrderRefundTemplate(Record member, Record order)
    {
        try
        {
            Record wxaConfig = getWxaConfig(order.getStr("shopId"));

            String templateKey = order.getStr("id") + "templateKey";
            Object obj = this.cache.get(templateKey);
            String prepay_id = obj.toString().substring(10);
            WxaTemplate wxaTemplate = new WxaTemplate();
            wxaTemplate.setForm_id(prepay_id);

            String sql = "SELECT * FROM ticket WHERE id='" + order.getStr("commodityId") + "'";
            Record ticket = Db.findFirst(sql);
            wxaTemplate.setTouser(member.getStr("openId"));
            wxaTemplate.setTemplate_id(wxaConfig.getStr("refundTemplateId"));
            wxaTemplate.add("keyword1", order.getStr("id"));
            wxaTemplate.add("keyword2", String.valueOf(ticket.get("name")));
            wxaTemplate.add("keyword3", DateUtils.getCurrDate());
            wxaTemplate.add("keyword4", order.getStr("money"));
            wxaTemplate.add("keyword5", "就是想退款");
            WxaTemplateApiRewrite wxaTemplateApi = new WxaTemplateApiRewrite();
            ApiResult apiResult = wxaTemplateApi.send(wxaTemplate, order.getStr("appId"));
            Syslog.info(apiResult.getJson());
        }
        catch (Exception e)
        {
            Syslog.error(e);
        }
    }

    public ReturnData addapplyRefund(Map<String, String[]> map)
    {
        String orderId = ((String[])map.get("orderId"))[0];
        String sql = "SELECT * FROM yx_apply_refund WHERE orderId='" + orderId + "'";
        Record record1 = Db.findFirst(sql);
        if (record1 != null) {
            return new ReturnData(false);
        }
        String id = UtilUUID.getUUID();
        String memberName = ((String[])map.get("memberName"))[0];
        String memberTel = ((String[])map.get("memberTel"))[0];

        String ticketId = ((String[])map.get("ticketId"))[0];
        String ticketName = ((String[])map.get("ticketName"))[0];
        String number = ((String[])map.get("number"))[0];
        String shopId = ((String[])map.get("shopId"))[0];
        String money = ((String[])map.get("money"))[0];
        String memberId = ((String[])map.get("memberId"))[0];

        Record record = new Record().set("id", id).set("state", "0").set("memberName", memberName).set("memberTel", memberTel).set("orderId", orderId).set("createTime", new Date()).set("ticketId", ticketId).set("ticketName", ticketName).set("number", number).set("shopId", shopId).set("money", money).set("memberId", memberId);

        boolean sa = Db.save("yx_apply_refund", record);

        return new ReturnData(sa);
    }

    public int numberRebates(String memberId, String orderId)
    {
        String sql = "SELECT COUNT(id) FROM yx_rebate_log WHERE  memberId='" + memberId + "' AND type='0' AND  to_days(createTime) = to_days(now()) AND errCodeDes='��������'";
        int num = Db.queryInt(sql).intValue();
        return num;
    }

    public ReturnData juniorMemberService(int page, String parentId)
    {
        String sql = "SELECT *from yx_member where parentId='" + parentId + "' and apply=2";

        String countSql = "SELECT count(*) from yx_member where parentId='" + parentId + "' and apply=2";

        PageUtil pageUtil = new PageUtil(page, 100, sql, countSql);

        List<Record> resultList = new ArrayList();
        for (int i = 0; i < pageUtil.getList().size(); i++)
        {
            Record temp = (Record)pageUtil.getList().get(i);

            String temporderSql = "SELECT\n\tCOUNT(*) as number ,IFNULL(SUM(money),0) as money \nFROM\n\tyx_order\nWHERE\n\tmemberId IN (\n\t\tSELECT\n\t\t\tid\n\t\tFROM\n\t\t\tyx_member\n\t\tWHERE\n\t\t\tparentId = '" + temp.getStr("id") + "'\n\t)";

            Record countRecord = Db.findFirst(temporderSql);

            temp.setColumns(countRecord);

            resultList.add(temp);
        }
        ReturnData returnData = new ReturnData(true);

        returnData.setData(resultList);

        return returnData;
    }



}
